package com.mdd.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1577836800L;

    private static final int COUNTS_BIT = 32;

    /**
     * 生成全局Id
     * @return
     */
     public Long nextId(String stringPrefix){
        //获取时间戳
        long now = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long time = now - BEGIN_TIMESTAMP;
        //获取序列号
        //获取当前日期精确到天
        String yyyyMMdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        Long increment = redisTemplate.opsForValue().increment("icr:" + stringPrefix + ":" + yyyyMMdd + ":");

        //拼接返回(通过位运算进行拼接)
        return time << COUNTS_BIT | increment;
    }
}
